package crap;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.TexturePaint;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import java.awt.geom.AffineTransform;
import java.awt.geom.NoninvertibleTransformException;
import java.awt.geom.Path2D;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;

import javax.imageio.ImageIO;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class SwingPath {
	public static void main(String[] args) throws Exception {
		JFrame ff = new JFrame();
		final Path2D path = new Path2D.Double();
		path.moveTo(1, 0);
		for (double i = 0; i<361; i++) {
			path.lineTo(200*Math.cos(Math.toRadians(i)), 200*Math.sin(Math.toRadians(i)));
		}
		
		path.closePath();
		
		final AffineTransform at = new AffineTransform();
		
//		at.preConcatenate(AffineTransform.getTranslateInstance(127, 127));
//		at.translate(100, 100);
		BufferedImage paint = ImageIO.read(Thread.currentThread().getContextClassLoader().getResourceAsStream("res/bild.jpg"));
		final TexturePaint tp = new TexturePaint(paint,new Rectangle2D.Double(-127, -127, paint.getWidth(), paint.getHeight()) );
		
		final JComponent a = new JComponent() {
			
		{setPreferredSize(new Dimension(256,256));}
			@Override
			public void paint(Graphics g) {
				Graphics2D g2 = (Graphics2D)g;
				g2.setTransform(at);
				g2.setPaint(tp);
//				g2.setColor(Color.red);
				g2.fill(path);
				super.paint(g);
			}
		};
		a.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				Point2D p = new Point2D.Double(e.getX(), e.getY());
				try {
					p = at.inverseTransform(p, p);
				} catch (NoninvertibleTransformException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				System.out.println(p);
				super.mouseClicked(e);
			}
		});
		a.addMouseWheelListener(new MouseWheelListener() {
			
			@Override
			public void mouseWheelMoved(MouseWheelEvent e) {
				
				double scale = Math.pow(1.01, e.getWheelRotation());

				try {
					Point2D p = new Point2D.Double(e.getX(), e.getY()); 
					at.inverseTransform(p, p);
					at.concatenate(AffineTransform.getTranslateInstance(p.getX(), p.getY()));
					at.concatenate(AffineTransform.getScaleInstance(scale, scale));
					at.concatenate(AffineTransform.getTranslateInstance(-p.getX(), -p.getY()));
				}
				catch (NoninvertibleTransformException nte ) {
					nte.printStackTrace();
				}
				System.out.println(at);
				a.repaint();
			}
		});
 		ff.add(a);
		
		ff.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
//		ff.pack();
		ff.setBounds(100, 100, 1000, 1000);
		ff.setVisible(true);
	}
}
